import { Store, Properties, Folder, Message } from "./index";
export const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));


export interface EmailClientOptions {
  host: string;
  port: number;
  user: string;
  password: string;
  protocol?: "imap" | "pop3";
  useTLS?: boolean;
}

export interface EmailInfo {
  uid: string;
  subject?: string;
  date?: number;
  from?: string;
  to?: string;
  text?: string;
  html?: string;
  headers?: any;
}

export class EmailClient {
  private store: Store;
  private inbox: Folder | null = null;

  constructor(private options: EmailClientOptions) {
    const props = new Properties(
      options.host,
      options.port,
      options.user,
      options.password,
      options.protocol || "imap",
      options.useTLS ?? true
    );
    this.store = new Store(props);
  }

  // 连接邮箱
  async connect() {
    await this.store.connect();
    // 默认获取INBOX文件夹
    this.inbox = await this.getInbox();
  }

  // 获取INBOX文件夹对象
  async getInbox(): Promise<Folder> {
    if (this.inbox) return this.inbox;
    const folders = await this.store.getFolders();
    const inbox = folders.find(f => f.getName().toUpperCase() === "INBOX");
    if (!inbox) throw new Error("INBOX文件夹不存在");
    this.inbox = inbox;
    return inbox;
  }

  // 获取最近N封邮件（默认10封）
  async getRecentEmails(count = 10): Promise<EmailInfo[]> {
    const inbox = await this.getInbox();
    const total = await inbox.open();
    const start = Math.max(1, total - count + 1);
    const messages = await inbox.getMessages([start, total]);
    await inbox.updateHeaders(messages);
    const result = await Promise.all(messages.map(async msg => {
      const body = await msg.fetchBody();
      return {
        ...msg['headers'],
        uid: msg.uid,
        ...body,
      };
    }));
    return result;
  }

  // 监听新邮件（轮询实现，interval单位ms，默认10秒）
  async listenNewMail(
    onMail: (mail: EmailInfo) => void,
    options?: { from?: string; interval?: number; timeout?: number }
  ) {
    const { from, interval = 10000, timeout = 5 * 60 * 1000 } = options || {};
    const inbox = await this.getInbox();
    let lastCount = await inbox.open();
    const startTime = Date.now();

    while (true) {
      await sleep(interval);
      const count = await inbox.open();
      if (count > lastCount) {
        // 新邮件到达
        const messages = await inbox.getMessages([count, count]);
        await inbox.updateHeaders(messages);
        for (const msg of messages) {
          const headers = msg['headers'];
          if (!from || (headers.from && headers.from.includes(from))) {
            // 提取正文内容
            const body = await msg.fetchBody();
            onMail({
              ...headers,
              uid: msg.uid,
              ...body, // 合并正文内容（html/text）
            });
            return; // 只监听一封，如需持续监听可去掉return
          }
        }
      }
      lastCount = count; // 始终更新lastCount
      if (Date.now() - startTime > timeout) {
        throw new Error("监听超时，未收到新邮件");
      }
    }
  }
}